﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CuaHangMayTinh.BusinessEntities;
using CuaHangMayTinh.BusinessLogicLayer;
using CuaHangMayTinh.Utilities;
using DevComponents.AdvTree;
using System.Threading;
using Microsoft.VisualBasic;

namespace CuaHangMayTinh.PresentationLayer
{
    /// <summary>
    /// hiển thị thông tin của form mặt hàng thêm, xóa, sửa tìm kiếm 
    /// </summary>
    public partial class FormMatHang : Form
    {
        private enum TinhTrang
        {
            Đang_trong_kho,
            Đã_bán,
            Đang_bảo_hành,
            Bị_lỗi,
            Đã_trả_hàng
        }

        /// <summary>
        /// tables chua danh sach entity
        /// </summary>
        public DataTable Table { get; set; }

        /// <summary>
        /// danh sachs mat hang can dung
        /// </summary>
        private List<MatHangEntity> matHangEntities;

        public string Text = string.Empty;

        /// <summary>
        /// khởi tạo form mặt hàng
        /// </summary>
        public FormMatHang()
        {
            InitializeComponent();
        }

        /// <summary>
        /// bắt sự kiện khi click vào một node
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void advTree1_NodeClick(object sender, DevComponents.AdvTree.TreeNodeMouseEventArgs e)
        {
            DataTable dt = DataUtil.ChangeColumn(MatHangManager.Find_TenLoaiMH(e.Node.ToString(),true));
            LoadListView(dt);
        }

        /// <summary>
        /// load lít view lên danh sách
        /// </summary>
        public void LoadListView()
        {
            dataGridViewX_Select.DataSource = MatHangManager.Find_All(true);
            if (dataGridViewX_Select.Columns.Count > 0)
            {
                dataGridViewX_Select.Columns[0].Visible = false;
            }
        }

        /// <summary>
        /// load datatable lên datagirview 
        /// </summary>
        /// <param name="dt"></param>
        public void LoadListView(DataTable dt)
        {
            dataGridViewX_Select.DataSource = dt;
            if (dataGridViewX_Select.Columns.Count > 0)
            {
                dataGridViewX_Select.Columns[0].Visible = false;
                if (dataGridViewX_Select.Columns.Contains(dataGridViewX_Select.Columns["T Trạng"]))
                {
                    dt.Columns.Add("T Trạng", typeof(string));
                    var t = dt.AsEnumerable().Where(x => x.Field<int>("Tình trạng") == 0);
                    foreach (var dataRow in t)
                    {
                        dataRow["T Trạng"] = "Đang trong kho";
                    }
                    var t1 = dt.AsEnumerable().Where(x => x.Field<int>("Tình trạng") == 1);
                    foreach (var dataRow in t1)
                    {
                        dataRow["T Trạng"] = "Đã bán";
                    }
                    var t2 = dt.AsEnumerable().Where(x => x.Field<int>("Tình trạng") == 2);
                    foreach (var dataRow in t2)
                    {
                        dataRow["T Trạng"] = "Đang bảo hành";
                    }
                    var t3 = dt.AsEnumerable().Where(x => x.Field<int>("Tình trạng") == 3);
                    foreach (var dataRow in t3)
                    {
                        dataRow["T Trạng"] = "Bị lỗi";
                    }
                    var t4 = dt.AsEnumerable().Where(x => x.Field<int>("Tình trạng") == 4);
                    foreach (var dataRow in t4)
                    {
                        dataRow["T Trạng"] = "Đã trả hàng";
                    }
                }
                dataGridViewX_Select.Columns["Tình trạng"].Visible = false;
            }
        }

        /// <summary>
        /// bắt sự kiện click của nút tìm kiếm
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btn_timkiem_click(object sender, EventArgs e)
        {
            FormMatHangTimKiem formMatHangTimKiem = new FormMatHangTimKiem(Table);
            formMatHangTimKiem.ShowDialog();
        }

        /// <summary>
        /// bắt sự kiện thay đổi text của textbox 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStriptxt_timnhanh_TextChanged(object sender, EventArgs e)
        {
            string text = (sender as ToolStripTextBox).Text;
            if (text != "")
            {
                DataTable dt = Table;
                var table2 =
                    dt.AsEnumerable().Where(x =>DataUtil.convertToUnSign3(x.Field<string>("Serial_code").ToLower())
                                    .StartsWith(DataUtil.convertToUnSign3(text.ToLower())));
                LoadListView(table2.Any() ? table2.CopyToDataTable() : null);
            }
            else
            {
                LoadListView(Table);
            }
        }

        /// <summary>
        /// sự kiện load form mặt hàng
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMatHang_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(() => (new Splash.Splash1()).ShowDialog());
            t.Start();
            Thread.Sleep(500);
            LoadTreeView();
            matHangEntities = new List<MatHangEntity>();
            if (advTree_listMatHang.Nodes.Count>0)
                advTree1_NodeClick(null, new TreeNodeMouseEventArgs(advTree_listMatHang.Nodes[0], MouseButtons.Left, 0, 0, 0, 0));
            Table = MatHangManager.Find_All(true);
            t.Abort();
        }

        void LoadTreeView()
        {
            advTree_listMatHang.DataSource = LoaiMatHangManager.Find_All();
            advTree_listMatHang.DisplayMembers = "TenLoaiMH";
            advTree_listMatHang.ValueMember = "MaLoaiMH";
        }

        private void toolStripBtn_TimKiem_Click(object sender, EventArgs e)
        {
            FormMatHangTimKiem tk = new FormMatHangTimKiem(Table);
            tk.ShowDialog();
        }

        private void báoLỗiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewX_Select.SelectedRows.Count > 0)
            {
                if ((int)dataGridViewX_Select.SelectedRows[0].Cells[8].Value == 0)
                {
                    //sửa thông tin mặt hàng
                    var row = dataGridViewX_Select.SelectedRows[0];
                    DataTable dt = MatHangManager.Find_ID((int)row.Cells[0].Value, false);
                    if (!(dt.Rows[0][3] is int))
                        dt.Rows[0][3] = 0;
                    if (!(dt.Rows[0][4] is int))
                        dt.Rows[0][4] = 0;
                    if (!(dt.Rows[0][5] is int))
                        dt.Rows[0][5] = 0;
                    MatHangEntity entity =
                        MatHangManager.ConvertToList(dt)[0];
                    entity.TinhTrang = 3;
                    if (MatHangManager.Update_TinhTrang(entity, ref Text))
                    {
                        MessageBox.Show("Cập nhật thành công !");
                        advTree1_NodeClick(null,new TreeNodeMouseEventArgs(advTree_listMatHang.SelectedNode,MouseButtons.Left,0,0,0,0));
                    }
                    else
                    {
                        MessageBox.Show(Text);
                    }
                    return;
                }
                if ((int) dataGridViewX_Select.SelectedRows[0].Cells[8].Value == 3)
                {
                    var row = dataGridViewX_Select.SelectedRows[0];
                    DataTable dt = MatHangManager.Find_ID((int)row.Cells[0].Value, false);
                    if (!(dt.Rows[0][3] is int))
                        dt.Rows[0][3] = 0;
                    if (!(dt.Rows[0][4] is int))
                        dt.Rows[0][4] = 0;
                    if (!(dt.Rows[0][5] is int))
                        dt.Rows[0][5] = 0;
                    MatHangEntity entity =
                        MatHangManager.ConvertToList(dt)[0];
                    entity.TinhTrang = 0;
                    if (MatHangManager.Update_TinhTrang(entity, ref Text))
                    {
                        MessageBox.Show("Cập nhật thành công !");
                        advTree1_NodeClick(null, new TreeNodeMouseEventArgs(advTree_listMatHang.SelectedNode, MouseButtons.Left, 0, 0, 0, 0));
                    }
                    else
                    {
                        MessageBox.Show(Text);
                    }
                }
            }
        }

        private void sửaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewX_Select.SelectedRows.Count > 0)
            {
                if ((int)dataGridViewX_Select.SelectedRows[0].Cells[8].Value == 0)
                {
                    //sửa thông tin mặt hàng
                    var row = dataGridViewX_Select.SelectedRows[0];
                    DataTable dt = MatHangManager.Find_ID((int)row.Cells[0].Value, false);
                    if (!(dt.Rows[0][3] is int))
                        dt.Rows[0][3] = 0;
                    if (!(dt.Rows[0][4] is int))
                        dt.Rows[0][4] = 0;
                    if (!(dt.Rows[0][5] is int))
                        dt.Rows[0][5] = 0;
                    MatHangEntity entity =
                        MatHangManager.ConvertToList(dt)[0];
                    string x = Interaction.InputBox("Serial", "Thông báo!", (string)row.Cells[2].Value);
                    if (StringHelper.IsNullorEmpty(x))
                        return;
                    entity.Serial_Code = x;
                    if (MatHangManager.Update_Serial(entity, ref Text))
                    {
                        MessageBox.Show("Cập nhật thành công !");
                        advTree1_NodeClick(null, new TreeNodeMouseEventArgs(advTree_listMatHang.SelectedNode, MouseButtons.Left, 0, 0, 0, 0));
                    }
                    else
                    {
                        MessageBox.Show(Text);
                    }
                }
                else
                {
                    MessageBox.Show("Không thể sửa mặt hàng này !");
                }
            }
            
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (dataGridViewX_Select.SelectedRows.Count > 0)
            {
                if ((int) dataGridViewX_Select.SelectedRows[0].Cells[8].Value == 0)
                {
                    báoLỗiToolStripMenuItem.Enabled = true;
                    sửaToolStripMenuItem.Enabled = true;
                    báoLỗiToolStripMenuItem.Text = "Báo lỗi";
                }
                if ((int) dataGridViewX_Select.SelectedRows[0].Cells[8].Value == 3)
                {
                    báoLỗiToolStripMenuItem.Text = "Cho Bán lại";
                }
            }
        }
    }
}
